<html>
    <head>
        <title>Itowns - Stereo</title>

        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="css/example.css">
        <link rel="stylesheet" type="text/css" href="css/LoadingScreen.css">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
    </head>
    <body>
        <div id="viewerDiv">
          <span id="divScaleWidget"> Scale </span>
        </div>
        </div>
        <script src="js/GUI/GuiTools.js"></script>
        <script src="../dist/itowns.js"></script>
        <script src="js/GUI/LoadingScreen.js"></script>
        <script src="../dist/debug.js"></script>
        <script type="text/javascript">
            var THREE = itowns.THREE;
        </script>
        <script src="https://cdn.rawgit.com/mrdoob/three.js/dev/examples/js/effects/AnaglyphEffect.js"></script>
        <script src="https://cdn.rawgit.com/mrdoob/three.js/dev/examples/js/effects/ParallaxBarrierEffect.js"></script>
        <script src="https://cdn.rawgit.com/mrdoob/three.js/dev/examples/js/effects/StereoEffect.js"></script>
        <script type="text/javascript">
            // Define initial camera position
            var placement = {
                coord: new itowns.Coordinates('EPSG:4326', 2.351323, 48.856712),
                range: 25000000,
            }
            var promises = [];
            var effect;

            // `viewerDiv` will contain iTowns' rendering area (`<canvas>`)
            var viewerDiv = document.getElementById('viewerDiv');

            // Instanciate iTowns GlobeView*
            var view = new itowns.GlobeView(viewerDiv, placement);

            // Eye separation value
            var eyeSep = 0.064;

            // Save StereoCamera update function
            var fnUpdateStereoCamera = itowns.THREE.StereoCamera.prototype.update;

            setupLoadingScreen(viewerDiv, view);

            itowns.THREE.StereoCamera.prototype.update = function _update(camera) {
                this.cameraL.far = camera.far;
                this.cameraR.far = camera.far;
                this.cameraL.layers = camera.layers;
                this.cameraR.layers = camera.layers;
                this.eyeSep = eyeSep;
                fnUpdateStereoCamera.bind(this)(camera);
            };


            // Add one imagery layer to the scene
            // This layer is defined in a json file but it could be defined as a plain js
            // object. See Layer* for more info.
            itowns.Fetcher.json('./layers/JSONLayers/Ortho.json').then(function _(config) {
                var source = new itowns.WMTSSource(config.source);
                var layer = new itowns.ColorLayer(config.id, { source });
                view.addLayer(layer).then(menuGlobe.addLayerGUI.bind(menuGlobe));
            });
            // Add two elevation layers.
            // These will deform iTowns globe geometry to represent terrain elevation.
            function addElevationLayerFromConfig(config) {
                config.source = new itowns.WMTSSource(config.source);
                var layer = new itowns.ElevationLayer(config.id, config);
                view.addLayer(layer).then(menuGlobe.addLayerGUI.bind(menuGlobe));
            }
            itowns.Fetcher.json('./layers/JSONLayers/WORLD_DTM.json').then(addElevationLayerFromConfig);
            itowns.Fetcher.json('./layers/JSONLayers/IGN_MNT_HIGHRES.json').then(addElevationLayerFromConfig);

            /* eslint-disable no-unused-vars */
            function updateEyeSep(value) {
                eyeSep = value;

                if (!effect) return;

                view.notifyChange();
            }

            function disableEffect() {
                if (effect && effect.dispose) {
                    effect.dispose();
                }
                var g = view.mainLoop.gfxEngine;
                var size = g.getWindowSize();
                effect = null;
                view.render = null;
                g.renderer.setViewport(0, 0, size.x, size.y);
                view.notifyChange();
            }

            function enableEffect(_eff) {
                var size;
                var g = view.mainLoop.gfxEngine;
                var r = g.renderer;

                if (effect) {
                    disableEffect();
                }

                effect = _eff;
                size = view.mainLoop.gfxEngine.getWindowSize();
                effect.setSize(size.x, size.y);

                view.render = function render() {
                    r.clear();
                    effect.render(view.scene, view.camera.camera3D);
                };

                view.notifyChange();
            }

            /**
             * Activate an anaglyph effect to the view. With a pair of red/blue glasses, the
             * user can see the scene in 3D. See https://en.wikipedia.org/wiki/Anaglyph_3D
             * for more information about this effect.
             */
            function enableAnaglyph() {
                var _eff;
                if (effect instanceof THREE.AnaglyphEffect) return;
                _eff = new THREE.AnaglyphEffect(view.mainLoop.gfxEngine.renderer,
                    view.camera.camera3D);
                enableEffect(_eff);
            }

            /**
             * Activate a parallax effect to the view. With a pair of polarized glasses, the
             * user can see the scene in 3D. This effect works better on an adapted screen.
             * See https://en.wikipedia.org/wiki/Polarized_3D_system for more information
             * about this effect.
             */
            function enableParallax() {
                var _eff;
                if (effect instanceof THREE.ParallaxBarrierEffect) return;
                _eff = new THREE.ParallaxBarrierEffect(view.mainLoop.gfxEngine.renderer,
                    view.camera.camera3D);
                enableEffect(_eff);
            }

            /**
             * Activate a stereo effect to the view.
             */
            function enableStereo() {
                var _eff;
                if (effect instanceof THREE.StereoEffect) return;
                _eff = new THREE.StereoEffect(view.mainLoop.gfxEngine.renderer,
                    view.camera.camera3D);
                enableEffect(_eff);
            }

            var menuGlobe = new GuiTools('menuDiv', view);
            var divScaleWidget = document.getElementById('divScaleWidget');

            var d = new debug.Debug(view, menuGlobe.gui);
            debug.createTileDebugUI(menuGlobe.gui, view, view.tileLayer, d);

            const stereoeffect = {
                none: disableEffect,
                anaglyph: enableAnaglyph,
                parallax: enableParallax,
                stereo: enableStereo,
                eyeSep: 0.064,
            };

            const folder = menuGlobe.gui.addFolder('Stereo Effect');
            folder.open();
            folder.add(stereoeffect, 'none').name('disable effect');
            folder.add(stereoeffect, 'anaglyph').name('enable Anaglyph effect');
            folder.add(stereoeffect, 'parallax').name('enable Parallax effect');
            folder.add(stereoeffect, 'stereo').name('enable Stereo effect');
            const guiEyeSep = folder.add(stereoeffect, 'eyeSep', 0, 0.2).name('Eye separator');

            guiEyeSep.onChange(updateEyeSep);

            function updateScaleWidget() {
                var value = view.getPixelsToMeters(200);
                value = Math.floor(value);
                var digit = Math.pow(10, value.toString().length - 1);
                value = Math.round(value / digit) * digit;
                var pix = view.getMetersToPixels(value);
                var unit = 'm';
                if (value >= 1000) {
                    value /= 1000;
                    unit = 'km';
                }
                divScaleWidget.innerHTML = `${value} ${unit}`;
                divScaleWidget.style.width = `${pix}px`;
            }

            // Listen for globe full initialisation event
            view.addEventListener(itowns.GLOBE_VIEW_EVENTS.GLOBE_INITIALIZED, function () {
                // eslint-disable-next-line no-console
                console.info('Globe initialized');
                updateScaleWidget();
            });
            view.controls.addEventListener(itowns.CONTROL_EVENTS.RANGE_CHANGED, () => {
                updateScaleWidget();
            });
        </script>
    </body>
</html>
